<template>


<!--  条件搜索-->
  <div style="display: flex; align-items: center; gap: 20px; padding: 10px 0;">
    <!-- 搜索框 -->
    <el-input
        v-model="searchName"
        placeholder="输入货物名称,回车以搜索"
        style="width: 300px; flex-shrink: 0;"
        @keyup.enter="searchByName"
    >
      <template #prepend>
        <el-icon><search /></el-icon>
      </template>
    </el-input>

    <!-- 日期选择器 -->
    <div style="flex-shrink: 0;">
      <el-date-picker
          v-model="timeValue"
          type="datetimerange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD HH:mm:ss"
          style="width: 380px;"
      />
    </div>

    <!-- 刷新按钮 - 增加min-width确保可见!!! -->
    <el-button
        type="primary"
        @click="changeTime(timeValue)"
        style="min-width: 80px; height: 32px;"
    >
      刷新
    </el-button>
  </div>

<!--货物展示-->
  <div style="width: 1250px">
    <el-table :data="tableData" style="width: 100%; height: 500px">
      <el-table-column fixed prop="id" label="货物 ID" width="100" align="center"></el-table-column>
      <el-table-column prop="name" label="货物名称" width="150" align="center"></el-table-column>
      <el-table-column prop="weight" label="货物重量" width="120" align="center"></el-table-column>
      <el-table-column prop="volume" label="货物体积" width="120" align="center"></el-table-column>
      <el-table-column prop="quality" label="品质" width="100" align="center">
        <template #default="scope">
          <el-tag :type="getQualityTagType(scope.row.quality)">
            {{ getQualityText(scope.row.quality) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="count" label="存货数量" width="120" align="center"></el-table-column>
      <el-table-column prop="wareHouseId" label="仓库 ID" width="100" align="center"></el-table-column>
      <el-table-column prop="updateTime" label="更新时间" width="180" align="center">
        <template #default="scope">
          {{ formatDate(scope.row.updateTime) }}
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div class="demo-pagination-block" style="margin-top: 15px">
    <el-pagination
        v-model:current-page="currentPage4"
        v-model:page-size="pageSize4"
        :page-sizes="[20, 50, 100, 200]"
        :size="size"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total=total
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
</template>

<script lang="ts" setup>
import {ref} from 'vue'
import axios from "axios"
import type {ComponentSize} from 'element-plus'
import {CaretLeft, CaretRight} from '@element-plus/icons-vue'


const tableData = ref([])
const currentPage4 = ref(1)
const pageSize4 = ref(20)
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)
const total = ref(0)
const searchName = ref('')
const timeValue = ref('')

axios.get(`http://localhost:8080/goods/findAll?pageNum=${currentPage4.value}&pageSize=${pageSize4.value}`).then(
    (res) => {total.value = res.data.total}
)
// 获取数据函数
async function fetchData() {
  const res = await axios.get(`http://localhost:8080/goods/findAll?pageNum=${currentPage4.value}&pageSize=${pageSize4.value}`)
  tableData.value = res.data.data
  total.value = res.data.total // 假设后端返回 total 字段
}

// 页面初始化加载数据
fetchData()

// 分页大小改变时触发
const handleSizeChange = (val: number) => {
  pageSize4.value = val
  changePage()
}

// 当前页码改变时触发
const handleCurrentChange = (val: number) => {
  currentPage4.value = val
  changePage()
}
function changePage(){
   axios.get(`http://localhost:8080/goods/findByName`,
      //携带参数
      {
        params: {
          name: searchName.value+"",
          pageNum: currentPage4.value,
          pageSize: pageSize4.value,
        }
      }
  ).then(
      (res) => {
        tableData.value = res.data.data
        total.value = res.data.total
      }
  )
}
//通过名称搜索
async function searchByName() {
  currentPage4.value = 1
  changePage()
}

// 格式化日期方法
const formatDate = (timestamp: number | string | Date): string => {
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 货物品质标签样式
const getQualityTagType = (quality: number): string => {
  switch (quality) {
    case 0:
      return 'success'
    case 1:
      return 'warning'
    case 2:
      return 'danger'
    default:
      return ''
  }
}

// 货物品质显示文本
const getQualityText = (quality: number): string => {
  switch (quality) {
    case 0:
      return '优质'
    case 1:
      return '良品'
    case 2:
      return '次品'
    default:
      return '未知'
  }
}

// 时间过滤函数
function changeTime(value: any) {
  //更新数据
  currentPage4.value = 1
  axios.get(`http://localhost:8080/goods/findByName`,
      //携带参数
      {
        params: {
          name: searchName.value + "",
          pageNum: currentPage4.value,
          pageSize: pageSize4.value,
        }
      }
  ).then(
      (res) => {
        tableData.value = res.data.data
        total.value = res.data.total
        if (!Array.isArray(value) || value.length < 2) {
          console.error("Invalid time range value");
          return;
        }

        // 2. 解析日期范围 - 支持多种输入类型
        const parseInputDate = (input: any): Date => {
          // 如果已经是 Date 对象，直接返回
          if (input instanceof Date) {
            return new Date(input);
          }

          // 如果是字符串，尝试清理并解析
          if (typeof input === 'string') {
            const cleaned = input
                .replace(/GHT|\(标准时间\)/g, '')
                .trim();
            return new Date(cleaned);
          }

          // 如果是数字（时间戳）
          if (typeof input === 'number') {
            return new Date(input);
          }

          // 其他情况返回无效日期
          console.error('Unsupported date type:', input);
          return new Date(NaN);
        };

        const startDate = parseInputDate(value[0]);
        const endDate = parseInputDate(value[1]);

        // 3. 验证日期有效性
        if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
          console.error("Invalid date range", value);
          return;
        }

        // 设置结束时间为当天的最后一毫秒
        endDate.setHours(23, 59, 59, 999);

        // 4. 过滤数据 - 保留在时间区间内的数据
        const filteredData = tableData.value.filter((item: any) => {
          if (!item?.updateTime) return false;

          try {
            const dbDate = new Date(item.updateTime);
            if (isNaN(dbDate.getTime())) return false;

            const itemTime = dbDate.getTime();
            return itemTime >= startDate.getTime() && itemTime <= endDate.getTime();
          } catch (e) {
            console.warn("Invalid date format:", item.updateTime);
            return false;
          }
        });

        // 5. 更新当前显示的表格数据
        tableData.value = filteredData;
        total.value = filteredData.length;
      }
  )
  // 1. 安全检查输入
}
</script>


<style scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
.demo-datetime-picker-icon {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
  justify-content: space-around;
  align-items: stretch;
}
.demo-datetime-picker-icon .block {
  padding: 30px 0;
  text-align: center;
}

.search{
  width: 200px;
  height: 35px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-right:20px
}

</style>